package com.dituhui.web;

import java.util.Hashtable;
import java.util.Map;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/wxsocket")
public class Socket {
	static Map<String, Session> sessionMap = new Hashtable<String, Session>();

	@OnOpen
	public void onOpen(Session session) {
		System.out.println("[onOpen] session=" + session.getId());
		sessionMap.put(session.getId(), session);
	}

	@OnMessage
	public void onMessage(String unscrambledWord, Session session) {
		System.out.println(unscrambledWord + ",session=" + session.getId());
//		broadcastAll("message", unscrambledWord);
	}

//	/**
//	 * 广播给所有人
//	 * 
//	 * @param message
//	 */
//	public static void broadcastAll(String type, String message) {
//		Set<Map.Entry<String, Session>> set = sessionMap.entrySet();
//		for (Map.Entry<String, Session> i : set) {
//			try {
//				i.getValue().getBasicRemote().sendText("{type:'" + type + "',text:'" + message + "'}");
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}

	@OnClose
	public void onClose(Session session, CloseReason closeReason) {
		sessionMap.remove(session.getId());
		System.out.println(String.format("Session %s closed because of %s", session.getId(), closeReason));
	}

	@OnError
	public void error(Session session, java.lang.Throwable throwable) {
		sessionMap.remove(session.getId());
		System.err.println("session " + session.getId() + " error:" + throwable);
	}

}
